<?php

namespace App\Http\Controllers\Steel;

use AlibabaCloud\SDK\Dingtalk\Vedu_1_0\Models\QueryClassScheduleResponseBody\config;
use App\Http\Controllers\BaseController;
use App\Http\Validate\Steel\SteelAttrList as SteelSteelAttrList;
use App\Models\Steel\SteelAttrList;
use App\Models\Steel\SteelAttrType;
use App\Models\Steel\SteelMaterialPriceCustom;
use App\Models\Steel\SteelMaterialPriceSupply;
use App\Services\Chanjet\TplusExcelExport;
use Illuminate\Http\Request;

use Maatwebsite\Excel\Facades\Excel;
use App\Services\Common\CommonExcelExport;

/**
 * 钢材属性相关
 */
class SteelAttrListController extends BaseController
{
    /**
     * 获取指定分类属性列表
     */
    public function getlist(Request $request)
    {
        $type_id = $request->type_id ?? 1;
        $status = $request->status ?? 0;
        $isgetall = $request->isgetall ?? 0;
        $steel_attr_type = SteelAttrType::where([['id', $type_id]])->whereIn('cpid', [0, $this->mangerinfo['cpid']])->first();
        if (!$steel_attr_type) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $list = SteelAttrList::getListByCompany($request, $this->mangerinfo['cpid'], $type_id, $status, $isgetall);
        if ($type_id == 2) {
            $config_arr = config('steelconfig.steel_type_2');
            foreach ($list['list'] as &$val) {
                if (in_array($val['attr_val_name'], $config_arr)) {
                    $val['is_red'] = 2;
                } else {
                    $val['is_red'] = 1;
                }
            }
        }



        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 新增指定分类属性
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['type_id', 'attr_no', 'attr_val_name']);

        $Validate = new SteelSteelAttrList();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $steel_attr_type = SteelAttrType::where([['id', $req_data['type_id']]])->whereIn('cpid', [0, $this->mangerinfo['cpid']])->first();
        if (!$steel_attr_type) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $isexist = SteelAttrList::where([['attr_no', $req_data['attr_no']], ['type_id', $req_data['type_id']], ['cpid', $this->mangerinfo['cpid']]])->orWhere([['attr_val_name', $req_data['attr_val_name']], ['type_id', $req_data['type_id']], ['cpid', $this->mangerinfo['cpid']]])->first();

        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '编码、名称不允许重复']);
        }

        $data = [
            'cpid' => $this->mangerinfo['cpid'],
            'type_id' => $req_data['type_id'],
            'attr_no' => $req_data['attr_no'],
            'attr_val_name' => $req_data['attr_val_name'],
            'update_at' => time()
        ];
        $data['create_at'] = time();

        $insert_id = SteelAttrList::create($data)->id;

        //属性分类为材质的时候添加基价相关
        if ($req_data['type_id'] == 2) {
            $pricedata = [
                'cpid' => $this->mangerinfo['cpid'],
                'material_attr_id' => $insert_id,
                'material_attr_no' => $req_data['attr_no'],
                'material_attr_name' => $req_data['attr_val_name'],
                'create_at' => time(),
                'update_at' => time()
            ];
            SteelMaterialPriceCustom::create($pricedata);
            SteelMaterialPriceSupply::create($pricedata);
        }


        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     * 冻结
     */
    public function changestatus(Request $request)
    {

        $id = $request->id ?? 0;
        $info = SteelAttrList::where([['id', $id], ['cpid', $this->mangerinfo['cpid']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $status = 2;
        SteelAttrList::where([['id', $id]])->update(['status' => $status, 'update_at' => time()]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 模板下载
     */
    public function dodownload(Request $request)
    {
        $filenmame = '/template/属性导入模板.xlsx';
        if ($filenmame != '' && file_exists(storage_path() . $filenmame) && is_file(storage_path() . $filenmame)) {
            ob_clean();
            return response()->download(storage_path() . $filenmame);
        } else {
            return response()->json(['code' => '001', 'msg' => '文件不存在，下载失败'], 200);
        }
    }

    /**
     * 上传导入，先调用uploadfile,返回地址调用该接口
     */
    public function doimport(Request $request)
    {
        set_time_limit(0);
        $filepathname = $request->filepathname;
        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
            $file = storage_path() . $filepathname;
            $data = Excel::toArray(null, $file)[0]; //获取sheet1
            $type_id = $request->type_id ?? 1;
            $steel_attr_type = SteelAttrType::where([['id', $type_id]])->whereIn('cpid', [0, $this->mangerinfo['cpid']])->first();
            if (!$steel_attr_type) {
                return response()->json(['code' => '001', 'msg' => '参数错误']);
            }
            //处理上传的数据
            $success_count = 0;
            $fail_count = 0;
            foreach ($data as $key => $val) {
                if ($key == 0) { //表头跳过
                    continue;
                }

                if(strlen($val[0])>30 || strlen($val[1])>60 || mb_strlen($val[0],'utf-8')>20 || mb_strlen($val[1],'utf-8')>30){
                    $fail_count++;
                    continue;
                }

                if($val[0]=='' || $val[1]==''){
                    $fail_count++;
                    continue;
                }


                $isexist = SteelAttrList::where([['attr_no', strval($val[0])], ['type_id', $type_id], ['cpid', $this->mangerinfo['cpid']]])
                    ->orWhere([['attr_val_name', $val[1]], ['type_id', $type_id], ['cpid', $this->mangerinfo['cpid']]])->first();
                if ($isexist) { //如有已存在属性，则跳过
                    $fail_count++;
                    continue;
                }

                $data = [
                    'cpid' => $this->mangerinfo['cpid'],
                    'type_id' => $type_id,
                    'attr_no' => strval($val[0]),
                    'attr_val_name' => $val[1],
                    'update_at' => time(),
                    'create_at' => time()
                ];
                $insert_id = SteelAttrList::create($data)->id;

                //属性分类为材质的时候添加基价相关
                if ($type_id == 2) {
                    $pricedata = [
                        'cpid' => $this->mangerinfo['cpid'],
                        'material_attr_id' => $insert_id,
                        'material_attr_no' => strval($val[0]),
                        'material_attr_name' => $val[1],
                        'create_at' => time(),
                        'update_at' => time()
                    ];
                    SteelMaterialPriceCustom::create($pricedata);
                    SteelMaterialPriceSupply::create($pricedata);
                }
                $success_count++;
            }

            return response()->json(['code' => '000', 'msg' => '数据导入成功：' . $success_count . '失败：' . $fail_count]);
        } else {
            return response()->json(['code' => '001', 'msg' => '文件不存在'], 200);
        }
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        $type_id = $request->type_id ?? 1;

        $steel_attr_type = SteelAttrType::where([['id', $type_id]])->whereIn('cpid', [0, $this->mangerinfo['cpid']])->first();
        if (!$steel_attr_type) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $list = SteelAttrList::getListByCompany($request, $this->mangerinfo['cpid'], $type_id, 0, 1);
        $exceldata = [];
        $row = [
            [
                'id' => '序号',
                'attr_no' => '编码',
                'attr_val_name' => '名称',
                // 'status' => '状态',
            ]
        ];

        foreach ($list['list'] as $key => $val) {
            $row[] = [
                'id' => $key + 1,
                'attr_no' => $val['attr_no'],
                'attr_val_name' => $val['attr_val_name'],
                // 'status' => $val['status'] == 1 ? '正常' : '冻结',
            ];
        }

        $datawith = [];
        $filename = $steel_attr_type->typename . '导出.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata, $datawith), $filename);
    }

    /****
     *  T+钢厂导出
     *
     */
    public function doexportsteelfactory(){
        $mangerinfo = $this->mangerinfo;
        $file_path = "钢厂.xlsx";
        $file_name = '钢厂';
        $newData = [];
        SteelAttrList::where(['cpid'=>$mangerinfo['cpid'],'type_id'=>'3'])->select('attr_no', 'attr_val_name','status')->get()
            ->each(function($item, $key) use (&$newData){
                $newData[] = [
                    'Code' => $item['attr_no'],
                    'Name' => $item['attr_val_name'],
                    'disabled' => (int)$item['status']-1,
                ];
        });
        $TplusExcelExport = new TplusExcelExport($file_path,'2',$newData,$file_name);
        return $TplusExcelExport->appendToExcel();
    }
    /****
     *  T+材质导出
     *
     */
    public function doexportmaterial(){
        $mangerinfo = $this->mangerinfo;
        $file_path = "材质.xlsx";
        $file_name = '材质';
        $newData = [];
        SteelAttrList::where(['cpid'=>$mangerinfo['cpid'],'type_id'=>'2'])->select('attr_no', 'attr_val_name','status')->get()
            ->each(function($item, $key) use (&$newData){
                $newData[] = [
                    'Code' => $item['attr_no'],
                    'Name' => $item['attr_val_name'],
                    'disabled' => (int)$item['status']-1,
                ];
            });
        $TplusExcelExport = new TplusExcelExport($file_path,'2',$newData,$file_name);
        return $TplusExcelExport->appendToExcel();
    }
    /****
     *  T+品种导出
     *
     */
    public function doexportbreed(){
        $mangerinfo = $this->mangerinfo;
        $file_path = "品种.xlsx";
        $file_name = '品种';
        $newData = [];
        SteelAttrList::where(['cpid'=>$mangerinfo['cpid'],'type_id'=>'1'])->select('attr_no', 'attr_val_name','status')->get()
            ->each(function($item, $key) use (&$newData){
                $newData[] = [
                    'Code' => $item['attr_no'],
                    'Name' => $item['attr_val_name'],
                    'disabled' => (int)$item['status']-1,
                ];
            });
        $TplusExcelExport = new TplusExcelExport($file_path,'2',$newData,$file_name);
        return $TplusExcelExport->appendToExcel();
    }
}
